/**
 * Created by kule on 2017/7/3.
 */

import set from 'lodash/set';


//genFnReg('getComponent|getZoom');
const genFnReg = (fnNames) => {
    return new RegExp(`(${fnNames})\\((.*?)\\)`);
};
const genFnExecReg = (fnNames) => {
    return new RegExp(`\.(${fnNames})\\((.*?)\\)`);
};

const getArgs=(str)=>{
    if(!str){
        return[];
    }
    return str.split(',');
};

//fnKeyPathGet(obj,'a.b.getComponent(mj,1,3).e','getComponent|getNode');
export const fnKeyPathGet = (obj, keyPath, reg) =>{
    const rst = {
        result: obj,
        prev: null
    };
    if (!keyPath) {
        return rst;
    }
    const _reg=(typeof reg=='string')?genFnReg(reg):reg;
    const keys = keyPath.split('.');
    let result = obj;
    let prev = null;
    let key;
    for (let i = 0, il = keys.length; i < il; i++) {
        key = keys[i];
        const match = key.match(_reg);

        prev = result;
        if (!match) {
            result = result[key];
        } else {
            result = result[match[1]](...getArgs(match[2]));
        }
    }
    return {
        result,
        prev,
        lastKey:key
    };
};

export const fnKeyPathSet=(obj,map,fnNames)=>{
    const reg=genFnReg(fnNames);
    for(let key in map){
        if(!reg.test(key)){
            set(obj,key,map[key]);
            continue;
        }
        let {result,prev,lastKey}=fnKeyPathGet(obj,key,reg);
        if(!prev){
            continue;
        }
        prev[lastKey]=map[key];
    }
};
export default fnKeyPathSet;